﻿using Common.Logging;
using LoveEat.Helper;
using LoveEat.MODEL;
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using System.Linq;
using System.Web;
using Common;
using System.Collections.Generic;
using Common.Extensions;

namespace LoveEat.AdminController
{
    public class BusinessManagementController : BaseController
    {

        private readonly ILog _fileLog = LogManager.GetLogger(typeof(BusinessManagementController));
        #region 店铺管理
        public ActionResult Shop(PageFilter filter, string shop_name)
        {
            var where = PredicateBuilder.True<shop>();
            //Expression<Func<shop, bool>> exp = a => true;
            if (!string.IsNullOrEmpty(shop_name))
            {

                where = where.And(p => p.shop_name == shop_name);
            }
            where = where.And(p => p.status == 1);
            var shopPageList = OperateContext.Current.BLLSession.IshopBLL.
                              GetPagedList(filter.PageIndex, filter.PageSize,
                              ref RowCount,
                            where, s => s.shop_id);
            Webdiyer.WebControls.Mvc.PagedList<shop> pageList = shopPageList.ToPagedList(filter.PageIndex, filter.PageSize);
            pageList.TotalItemCount = RowCount;
            pageList.CurrentPageIndex = filter.PageIndex;
            return View(pageList);
        }

        [HttpGet]
        public ActionResult ShopEdit(shop model)
        {
            List<common_area> list = new List<common_area>();
            if (model.shop_id > 0)
            {
                model = OperateContext.Current.BLLSession.IshopBLL.GetListBy(s => s.shop_id == model.shop_id).FirstOrDefault();
                list = OperateContext.Current.BLLSession.Icommon_areaBLL.GetListBy(s => s.ParentId == model.provinces_id).ToList();
                ViewBag.region_idList = new SelectList(OperateContext.Current.BLLSession.Icommon_areaBLL.GetListBy(s => s.ParentId == model.city_id).ToList(), "AreaId", "AreaName").AsEnumerable();
            }
            else
            {
                ViewBag.region_idList = new SelectList(list, "AreaId", "AreaName").AsEnumerable();
            }
            ViewBag.city_idList = new SelectList(list, "AreaId", "AreaName").AsEnumerable();
            ViewBag.provincesList = new SelectList(OperateContext.Current.BLLSession.Icommon_areaBLL.GetListBy(s => s.ActiveStatus == 1 && s.ParentId == 0).ToList(), "AreaId", "AreaName").AsEnumerable();

            return View(model);
        }

        [HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ShopEdit(LoveEat.MODEL.shop model, string returnUrl, HttpPostedFileBase imageUpLoad)
        {
            #region 图片上传
            string pImgSrc = string.Empty;
            if (imageUpLoad != null)
            {
                if (!imageUpLoad.ContentType.Contains("image/"))
                {
                    return Content(AlterMessage("请上传正确的图片", returnUrl));
                }

                //1.2验证图片大小
                if (imageUpLoad.ContentLength <= 2 || imageUpLoad.ContentLength > 4 * 1024 * 1024)
                {
                    return Content(AlterMessage("图片太小或太大（1M以内）~！", returnUrl));
                }
                //1.2 生成 新的图片名
                pImgSrc = FileHelper.NewFileName(imageUpLoad.FileName);
                //1.3 生成 缩略图变名
                //    string strNewThumbName = FileHelper.GetThumbName(strNewImgName);

                ////2.保存图片 和 生成缩略图
                FileHelper.SaveImgAndThumb(imageUpLoad, pImgSrc, "/upload/image/shop/", 145, 145);
            }
            #endregion
            var result = 0;
            if (ModelState.IsValid)
            {
                model.updateTime = DateTime.Now;
                if (model.shop_id > 0) //update
                {
                    if (imageUpLoad != null)
                    {
                        model.shop_icon = "/upload/image/shop/" + pImgSrc;
                    }
                    if (OperateContext.Current.BLLSession.IshopBLL.Update(model))
                    {
                        result = 1;
                    }

                }
                else //add
                {
                    model.status = 1;
                    model.shop_icon = "/upload/image/shop/" + pImgSrc;
                    result = OperateContext.Current.BLLSession.IshopBLL.Add(model);
                }
                if (result > 0)
                {

                    return Content(AlterMessage("操作成功", returnUrl));

                }
            }
            return Content(AlterMessage("操作失败", returnUrl));
        }

        public ActionResult DeleteShop(shop model, string returnUrl)
        {
            int result = OperateContext.Current.BLLSession.IshopBLL.Del(model);

            if (result > 0)
            {

                return Content(AlterMessage("删除成功", returnUrl));
            }
            return Content(AlterMessage("删除失败", returnUrl));
        }
        public ActionResult DeleteShopList(string id)
        {
            int[] ids = id.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();


            int result = OperateContext.Current.BLLSession.IshopBLL.DelBy(s
                => ids.Contains(s.shop_id));
            return Json(result);
        }
        /// <summary>
        /// 添加桌号
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <param name="shop_id"></param>
        /// <returns></returns>
        public ActionResult _AddSeat(string returnUrl, int shop_id)
        {
            ViewBag.returnUrl = returnUrl;
            ViewBag.shop_id = shop_id;
            return PartialView();
        }
        [HttpPost]
        public ActionResult Do_AddSeat(string returnUrl, seat model)
        {
            var result = 0;

            if (OperateContext.Current.BLLSession.IseatBLL.GetListBy(s => s.shop_id == model.shop_id && s.seat_number == model.seat_number).FirstOrDefault() != null)
            {
                return Content(AlterMessage("已经存在该桌位号", returnUrl));
            }
            if (model.seat_id > 0)
            {
                if (OperateContext.Current.BLLSession.IseatBLL.Update(model))
                {
                    result = 1;
                }
            }
            else
            {
                result = OperateContext.Current.BLLSession.IseatBLL.Add(model);
            }
            if (result > 0)
            {
                return Content(AlterMessage("操作成功", returnUrl));

            }
            return Content(AlterMessage("操作失败", returnUrl));
        }


        #endregion

        #region 账号管理
        public ActionResult Employee(PageFilter filter, string account)
        {
            var where = PredicateBuilder.True<employee>();
            Expression<Func<shop, bool>> exp = a => true;
            if (!string.IsNullOrEmpty(account))
            {
                where = where.And(p => p.account == account);
            }
            where = where.And(p => p.status == 1);
            List<employee> employeePageList = OperateContext.Current.BLLSession.IemployeeBLL.
                              GetPagedList(filter.PageIndex, filter.PageSize,
                              ref RowCount,
                            where, s => s.shop_id);
            // OperateContext.Current.BLLSession.IshopBLL.GetListBy(p => p.shop_id == s.shop_id
            foreach (var item in employeePageList)
            {
                var shop = OperateContext.Current.BLLSession.IshopBLL.GetListBy(p => p.shop_id == item.shop_id).FirstOrDefault();

                item.ShopName = shop != null ? shop.shop_name : item.ShopName;
            }
            Webdiyer.WebControls.Mvc.PagedList<employee> pageList = employeePageList.ToPagedList(filter.PageIndex, filter.PageSize);
            pageList.TotalItemCount = RowCount;
            pageList.CurrentPageIndex = filter.PageIndex;
            return View(pageList);
        }
        [HttpGet]
        public ActionResult EmployeeEdit(MODEL.employee model)
        {
            List<common_area> list = new List<common_area>();
            if (model.employee_id > 0)
            {
                model = OperateContext.Current.BLLSession.IemployeeBLL.GetListBy(s => s.status == 1 && s.employee_id == model.employee_id).FirstOrDefault();

            }

            ViewBag.ShopList = new SelectList(OperateContext.Current.BLLSession.IshopBLL.GetListBy(s => s.status == 1).ToList(), "shop_id", "shop_name").AsEnumerable();
            ViewBag.employeeTypeLis = EnumExtension.ToSelectListOthers<LoveEat.Enum.AdminEnum.employeeType>(model.employeeType);
            return View(model);
        }
        [HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EmployeeEdit(MODEL.employee model, string returnUrl)
        {
            var result = 0;
            if (ModelState.IsValid)
            {
                model.updateTime = DateTime.Now;
                if (model.shop_id > 0) //update
                {
                    if (OperateContext.Current.BLLSession.IemployeeBLL.Update(model))
                    {
                        result = 1;
                    }
                }
                if (result > 0)
                {
                    return Content(AlterMessage("操作成功", returnUrl));
                }
            }
            return Content(AlterMessage("操作失败", returnUrl));
        }
        public ActionResult DeleteEmployee(employee model, string returnUrl)
        {
            int result = OperateContext.Current.BLLSession.IemployeeBLL.Del(model);

            if (result > 0)
            {
                return Content(AlterMessage("删除成功", returnUrl));
            }
            return Content(AlterMessage("删除失败", returnUrl));
        }
        public ActionResult DeleteEmployeeList(string id)
        {
            int[] ids = id.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
            int result = OperateContext.Current.BLLSession.IemployeeBLL.DelBy(s
                           => ids.Contains(s.employee_id));
            return Json(result);
        }

        #endregion

        /// <summary>
        /// 审核账号
        /// </summary>
        /// <param name="employee_id"></param>
        /// <returns></returns>
        public ActionResult ExamineEmployee(string employee_ids, string returnUrl)
        {
            ViewBag.employee_ids = employee_ids;
            ViewBag.returnUrl = returnUrl;
            return PartialView();
        }
        /// <summary>
        /// 审核
        [HttpPost]
        public ActionResult DoExamineEmployee(string employee_ids, string returnUrl, int passStatus)
        {

            var result = new Result { IsError = true };
            if (string.IsNullOrEmpty(employee_ids))
            {
                return Content(AlterMessage("操作失败", returnUrl));
            }
            int[] ids = employee_ids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
            var model = OperateContext.Current.BLLSession.IemployeeBLL.GetListBy(s => ids.Contains(s.employee_id)).ToList();

            foreach (var item in model)
            {
                item.passStatus = passStatus;
            }

            if (OperateContext.Current.BLLSession.IemployeeBLL.Update(model))
            {
                return Content(AlterMessage("操作成功", returnUrl));
            }
            return Content(AlterMessage("操作失败", returnUrl));
        }

        /// <summary>
        /// 选择地区
        /// </summary>
        public ActionResult Common_areaList(int? parentId = 0)
        {

            var commonAreaList = OperateContext.Current.BLLSession.Icommon_areaBLL.GetListBy(s => s.ParentId == parentId && s.ActiveStatus == 1).ToList();

            return Json(commonAreaList, JsonRequestBehavior.AllowGet);
        }
    }
}
